package com.chinawayltd.ews.sample.web.basicInfo;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.model.TBranchConsumeTime;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.basicInfo.BranchConsumeTimeVO;
import com.chinawayltd.ews.sample.service.basicInfo.BranchConsumeTimeService;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.util.BaseController;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelGenerateModel;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExcelUtils;
import com.chinawayltd.ews.sample.web.query.BranchConsumeTimeGirdQuery;
import com.chinawayltd.ews.sample.web.query.LogGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 站点耗时信息管理
 * @author: chenxin
 * @create: 2018年4月11日 下午11:12:23
 */
@Api(tags = { "站点耗时信息管理API" })
@RestController
@RequestMapping(value = "/web/branch/consumeTime")
public class BranchConsumeTimeController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	BranchConsumeTimeService branchConsumeTimeService;
    @Autowired
    private CommonService commonService;
    
	@ApiOperation(value = "列表查询接口")
	@RequestMapping(value = "/loadGirdData", method = { RequestMethod.POST })
	public ResultModel loadGirdData(BranchConsumeTimeGirdQuery queryParam) {
		ResultModel model = new ResultModel();
		try {
			List<BranchConsumeTimeVO> list = branchConsumeTimeService.list(queryParam);
			model.setData(new JSONObject().fluentPut("result", list));
			model.setPage(queryParam);
		} catch (Exception e) {
			model.setSub_code(1);
			logger.error("站点耗时信息列表查询出错！", e);
		}
		return model;
	}
	
	@ApiOperation(value = "站点耗时信息ID查询接口")
	@RequestMapping(value = "/find/{id}", method = { RequestMethod.GET })
	@ApiImplicitParam(paramType = "path", name = "id", value = "站点耗时信息ID", dataType = "Long", required = true)
	public ResultModel getById(@PathVariable Long id) {
		ResultModel model = new ResultModel();
		try {
			TBranchConsumeTime data = branchConsumeTimeService.getById(id);
			model.setData(new JSONObject().fluentPut("result", data));
        } catch (Exception e){
        	model.setSub_code(ResultModel.SUB_CODE_SYSTEM_ERROR);
        	model.setSub_msg(e.getMessage());
        	logger.error("根据ID查询信息出错！id：" + id, e);
        }
		return model;
	}

	@ApiOperation(value = "站点耗时信息管理新增接口")
	@RequestMapping(value = "/add", method = { RequestMethod.POST })
	@ApiImplicitParams({
    	@ApiImplicitParam(paramType="query", name="startBranch",value="出发站点ID",dataType="Long",required=true),
    	@ApiImplicitParam(paramType="query", name="arniveBranch",value="到达站点ID",dataType="Long",required=true),
    	@ApiImplicitParam(paramType="query", name="vehicleModels",value="车型(板)",dataType="Long",required=true),
    	@ApiImplicitParam(paramType="query", name="travelTime",value="耗时时长",dataType="Long",required=true)
    })
	public ResultModel add(TBranchConsumeTime tBranchConsumeTime) {
		ResultModel model = new ResultModel();
		try {
			int result = branchConsumeTimeService.add(tBranchConsumeTime);
			if(result > 0){
				model.setData(new JSONObject().fluentPut("result", "添加成功"));
			}else{
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg" , "添加失败"));
			}
        } catch (BusinessException e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
		} catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "添加异常"));
        	logger.error("站点耗时信息管理新增发生异常！", e);
        }
		return model;
	}

	@ApiOperation(value = "站点耗时信息管理修改接口")
	@RequestMapping(value = "/update", method = { RequestMethod.POST })
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query", name="id",value="站点耗时信息ID",dataType="Long",required=true),
    	@ApiImplicitParam(paramType="query", name="startBranch",value="出发站点ID",dataType="Long",required=true),
    	@ApiImplicitParam(paramType="query", name="arniveBranch",value="到达站点ID",dataType="Long",required=true),
    	@ApiImplicitParam(paramType="query", name="vehicleModels",value="车型(板)",dataType="int",required=true),
    	@ApiImplicitParam(paramType="query", name="travelTime",value="耗时时长",dataType="int",required=true)
    })
	public ResultModel update(TBranchConsumeTime tBranchConsumeTime) {
		ResultModel model = new ResultModel();
		try {
			int result = branchConsumeTimeService.update(tBranchConsumeTime);
			if(result > 0){
				model.setData(new JSONObject().fluentPut("result", "修改成功"));
			}else{
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg" , "修改失败"));
			}
        } catch (BusinessException e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
		} catch (Exception e){
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "修改异常"));
        	logger.error("站点耗时信息管理修改发生异常！"+e);
        }
		return model;
	}

	@ApiOperation(value = "站点耗时信息管理删除接口")
	@RequestMapping(value = "/delete/{id}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "id", value = "站点耗时信息管理ID", dataType = "Long", required = true)
	public ResultModel delete(@PathVariable Long id) {
		ResultModel model = new ResultModel();
        try {
        	int result = branchConsumeTimeService.delete(id);
        	if(result >0){
				model.setData(new JSONObject().fluentPut("result", "删除成功!"));
			}else{
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg", "删除失败!"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "删除失败!"));
        	model.setSub_msg(e.getMessage());
			logger.error("删除信息发生异常！id="+id, e);
		}
		return model;
	}
	
	@ApiOperation(value = "批量删除接口")
	@RequestMapping(value = "/deleteAll/{ids}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "ids", value = "拼接需要删除的数据id串如：1,2,3,4", dataType = "String", required = true)
	public ResultModel deleteAll(@PathVariable String ids) {
		ResultModel model = new ResultModel();
		try {
			int result = branchConsumeTimeService.deletesByIds(ids);
			if(result >0){
				model.setData(new JSONObject().fluentPut("result", "删除成功!"));
			}else{
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg", "删除失败!"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "删除失败!"));
        	model.setSub_msg(e.getMessage());
        	logger.error("删除信息发生异常！ids="+ids, e);
		}
		return model; 
	}
	
	@ApiOperation(value = "站点耗时信息管理导出接口")
    @RequestMapping(value = "/exportGirdData", method = { RequestMethod.POST })
    public void exportGirdData(@RequestBody BranchConsumeTimeGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<BranchConsumeTimeVO> branchList = branchConsumeTimeService.list(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(branchList)
                    .cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "站点耗时信息管理列表" , request, response);
        }catch (Exception e){
            logger.error("站点耗时信息管理列表导出出错！", e);
        }
    }
	
	/**
	 * 解析excel2003和2007的数据，并导入到数据库，错误数据导出到前台
	 * @author: chenxin
	 * @date: 2018年4月26日
	 * @param file
	 * @param request
	 * @param response
	 */
    @SuppressWarnings("rawtypes")
    @ApiOperation(value = "站点耗时信息批量导入")
	@RequestMapping(value="/readExcel", method = { RequestMethod.POST })
    public Object readExcel(@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
    	JSONObject object = new JSONObject();
    	try {
    		// 1、解析导入的数据
	    	ExcelObjModel model = ExcelUtils.readExcel(file);
			if(model.getCode() !=0){
	    		object.put("state", 400);
		    	object.put("msg", model.getMsg());
				return object.toString();
			}
			// 2、导入数据到数据库
			List<PageData> list = (List)model.getList();
			if(list ==null || list.isEmpty()){
				object.put("state", 400);
		    	object.put("msg", "导入的表不是有效的文件或数据为空");
		    	return object.toString();
			}
			ExcelObjModel result = branchConsumeTimeService.insertList(list);
			// 3、导出错误数据
			if(result.getList().size() >0){
		        ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(result.getList()).cloumnList(result.getCloums()).build();
		        Workbook workbook = ExcelUtils.generateExcel(excelModel);
				this.sendWorkbook(workbook, "站点耗时信息" , request, response);
			}
    	} catch (BusinessException e) {
		 	object.put("state", 400);
	    	object.put("msg", e.getMessage());
	    	return object.toString();
		} catch (IOException e) {
			object.put("state", 400);
	    	object.put("msg", "导入数据接口出错");
	    	return object.toString();
		} catch (Exception e) {
			logger.error("导入数据接口出错！", e);
		}
    	return null;
    }
    
    @ApiOperation(value = "通过ID查询操作日记接口,需要传id")
    @RequestMapping(value = "/getLogDataById", method = { RequestMethod.POST })
    public ResultModel getLogDataById(LogGirdQuery queryParam) {
		ResultModel model = new ResultModel();
		try {
			queryParam.setTableName("T_BRANCH_CONSUME_TIME");
            List<TLog> list = commonService.getLogDataById(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", null));
            logger.error("通过ID查询操作日记接口异常！", e);
        }
        return model;
    }
}
